/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.aratuk.servico;

import br.com.aratuk.modelo.Usuario;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author roniere
 */
public class ServicoGenerico<T> {

    @PersistenceContext
    private EntityManager entityManager;
    private Class<T> entity;

    public ServicoGenerico(Class<T> entity) {
        this.entity = entity;
    }

    public void save(T entity) {
        
        entityManager.persist(entity);
    }

    public void delete(T entity) {
        update(entity);
    }

    public void update(T entity) {
        entityManager.merge(entity);
        entityManager.flush();
    }

    public T find(Long entityID) {
        return entityManager.find(entity, entityID);
    }

    public List<T> findAll() {
        return entityManager.createQuery("select e from " + entity.getSimpleName() + " e where e.status = true order by e.id asc").getResultList();
    }

    public EntityManager getEntityManager() {
        return entityManager;
    }

    public Long quantidadeRegistros() {
        Long result = (Long) entityManager.createQuery("select count(e) from " + entity.getSimpleName() + " e").getSingleResult();

        return result != null ? result : 0;
    }

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public List<T> find(T t, Integer first, Integer pageSize) {
        String sql = "select e from " + entity.getSimpleName() + " e ";

        Query query = entityManager.createQuery(sql).setFirstResult(first).setMaxResults(pageSize);

        return query.getResultList();
    }

    /**
     * Resgata usuário logado no sistema
     *
     * @return
     */
    public Usuario verifySystemUserForLogin() {
        try {
            String nome = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName();

            if (nome != null && !nome.isEmpty()) {
                Usuario usr;

                final String sql = "select u from " + Usuario.class.getSimpleName() + " u where "
                        + "u.login like :nome and u.ativo = true";
                Query query = getEntityManager().createQuery(sql);
                query.setParameter("nome", nome);
                usr = (Usuario) query.getSingleResult();

                return usr;
            }
        } catch (Exception e) {
            Logger.getLogger(ServicoGenerico.class.getName()).log(Level.SEVERE, null, e);

            System.err.println(e);
        }
        return null;
    }
}

